/*
 * Copyright (c) 2004-2006 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gou Pengfei
 * Date:    April. 2011
 */

#ifndef __CPU_EDGE_GLOBAL_TYPE_HH__
#define __CPU_EDGE_GLOBAL_TYPE_HH__

#include <vector>
#include <deque>

#include "cpu/edge/pred/base_type_predictor.hh"
//#include "cpu/edge/pred/predictor_table.hh"
#include "cpu/edge/sat_counter.hh"

template<class Impl>
class GlobalTypeP : public BaseTypePredictor<Impl>
{
  public:
    typedef TheISA::BlockID BlockID;
    typedef TheISA::BTypeID BTypeID;
    typedef std::deque<Addr> PathHistory;

    enum TableMode {
        Normal,
        AliasFree,
        InvalidTableMode
    };

    enum GlobalIndexMode {
        Address,
        AddressAndPath,
        AddressAndCPath,
        AddressAndHist,
        AddressAndCHist,
        InvalidGlobalIndexMode
    };

    enum HysteresisMode {
        Symmetric,
        Asymmetric,
        InvalidHysteresisMode
    };

    GlobalTypeP(DerivEdgeCPUParams *params, std::string index_mode);

    ~GlobalTypeP();

    void reset();	

    /**
     * Looks up the given block address in the branch predictor and returns
     * an type ID of the block.
     */
    TheISA::BTypeID lookup(BlockID block_id, BlockID oldest_block_id, 
        Addr &block_addr, int addr_space_ID, ThreadID tid);   

    /**
     * Updates the branch predictor with the actual result of a branch.
     * Return the prediction before update.
     */
    TheISA::BTypeID update(BlockID block_id, Addr &block_addr, int addr_space_id,
                              BTypeID actual_type_id,ThreadID tid);

    /**
     * Restores the global branch history on a squash.
     */
    void squash(BlockID block_id, Addr block_pc, BTypeID type_id,
            ThreadID tid);

    /**
     * Restores the global branch history on a squash.
     */
    void squash(BlockID block_id,ThreadID tid);

    uint64_t getPathHistory(ThreadID tid);

    uint64_t getPathHistory(BlockID block_id, ThreadID tid);

    int getCounterBits() { return globalCtrBits; }

  private:

    struct PredictionTableEntry {
        PredictionTableEntry(BasePredictor<Impl> * ptr)
            : predictorPtr(ptr),
            typeID(1),
            hysteresis(ptr->getCounterBits())
        {}

	~PredictionTableEntry()
	{}

        BasePredictor<Impl> * predictorPtr;

	BTypeID typeID;
        SatCounter hysteresis;
    };

    void initVars();

    TableMode tableMode;

    GlobalIndexMode globalIndexMode;

    HysteresisMode hysteresisMode;

    inline uint64_t calcGloPredIdx(Addr &block_addr, uint64_t history,
            uint64_t path_hist);

    void updatePathHistory(PathHistory &path_history, Addr new_pc);

    void updateHysteresis(PredictionTableEntry &entry,
            BTypeID actual_type_id);

    /** Number of bits for global hysteresis. */
    int globalCtrBits;

    /** Array of counters that make up the global predictor. */
    PredictorTable<PredictionTableEntry, Impl> globalCtrs;

    /** Size of the global predictor. */
    uint64_t globalPredictorSize;

    /** Mask of the global predictor table. */
    uint64_t globalPredictorMask;

    /** Global history register. */
    uint64_t globalHistory[Impl::MaxThreads];

    /** Path histories of all threads, speculatively updated. */
    PathHistory pathHistoryTable[Impl::MaxThreads];

    /** Global history file. */
    std::vector<uint64_t> globalHistoryFile;

    /** Path histories of all in-flight blocks. */
    PathHistory pathHistoryFile[Impl::MaxInFlightBlockNum];

    /** Number of bits for the global history. */
    uint64_t globalHistoryBits;

    /** Mask to get the proper global history. */
    uint64_t globalHistoryMask;

    /** Number of bits to shift the instruction over to get rid of the word
     *  offset.
     */
    uint64_t blockShiftAmt;

    /** Threshold for global/local predictor; above the threshold we
     * can update the entry, equal to or below the threshold we can
     * not update.*/
    uint64_t threshold;

    /** Type id bits. */
    int typeIdBits;

    /** Type id mask. */
    uint64_t typeIdMask;
};

#endif // __CPU_EDGE_GLOBAL_TYPE_HH__
